import React, { useState } from 'react';
import {
  TextField,
  InputAdornment,
  Box,
  IconButton,
} from '@mui/material';
import { Folder as FolderIcon } from '@mui/icons-material';
import ActionDialog from './ActionDialog';
import Tooltip from '../../general/Tooltip';
import FileBrowser from '../../general/FileBrowser';
import Checkbox from '../../general/Checkbox';
import { NETPYNE_COMMANDS, MODEL_STATE, DEFAULT_CONFIRMATION_DIALOG_MESSAGE } from '../../../constants';
import { PYTHON_CALL } from '../../../constants';
import { useAppSelector, useAppDispatch } from '../../../redux/hooks';
import { openConfirmationDialog } from '../../../redux/slices/generalSlice';

interface ImportFileDialogProps {
  open?: boolean;
  onRequestClose?: () => void;
  title?: string;
  command?: string;
  extension?: string;
  modFileSelector?: boolean;
  modelState?: string;
  [key: string]: any;
}

/**
 * ImportFileDialog Component
 * Dialog for importing files (NeuroML, LEMS, Python scripts, etc.)
 * Supports file selection, mod folder selection, and compilation options
 */
const ImportFileDialog: React.FC<ImportFileDialogProps> = ({
  open = false,
  onRequestClose,
  title = 'Import File',
  command = NETPYNE_COMMANDS.importModel,
  extension = '',
  modFileSelector = false,
  modelState,
  ...otherProps
}) => {
  const dispatch = useAppDispatch();
  const currentModelState = modelState || useAppSelector((state) => state.general.modelState);
  
  const [fileName, setFileName] = useState<string | null>(null);
  const [modFolder, setModFolder] = useState('');
  const [loadMod, setLoadMod] = useState<boolean | undefined>(false);
  const [compileMod, setCompileMod] = useState(true);
  const [explorerDialogOpen, setExplorerDialogOpen] = useState(false);
  const [explorerParameter, setExplorerParameter] = useState('');
  const [exploreOnlyDirs, setExploreOnlyDirs] = useState(false);
  const [filterFiles, setFilterFiles] = useState<string | boolean>(false);

  const initialState = (): void => {
    setFileName(null);
    setModFolder('');
    setLoadMod(false);
    setCompileMod(true);
    setExplorerDialogOpen(false);
    setExplorerParameter('');
    setExploreOnlyDirs(false);
    setFilterFiles(false);
  };

  const isFormValid = (): boolean => {
    return loadMod !== undefined && loadMod !== false;
  };

  const showExplorerDialog = (param: string, onlyDirs: boolean, fileFilter?: string | boolean): void => {
    setExplorerDialogOpen(true);
    setExplorerParameter(param);
    setExploreOnlyDirs(onlyDirs);
    setFilterFiles(fileFilter || false);
  };

  const getDirAndModuleFromPath = (fullpath: string): { dirPath: string; moduleName: string } => {
    const fileName = fullpath.replace(/^.*[\\/]/, '');
    const moduleName = fileName.replace(/\.[^/.]+$/, '');
    const dirPath = fullpath.split(fileName).slice(0, -1).join('');

    return {
      dirPath,
      moduleName,
    };
  };

  const closeExplorerDialog = (fieldValue?: any): void => {
    setExplorerDialogOpen(false);
    if (fieldValue) {
      const { dirPath } = getDirAndModuleFromPath(fieldValue.path);
      
      if (explorerParameter === 'file') {
        setFileName(fieldValue?.path);
        setModFolder(dirPath);
      } else if (explorerParameter === 'modFolder') {
        setModFolder(fieldValue.path);
        setLoadMod(true);
      }
    }
  };

  const onFilePathChange = (fullpath: string): void => {
    setFileName(fullpath);
  };

  const onModFolderPathChange = (fullpath: string): void => {
    setModFolder(fullpath);
    setLoadMod(fullpath !== '');
  };

  const handleConfirmation = (command: string, args: Record<string, any>): void => {
    dispatch(
      openConfirmationDialog({
        title: 'Warning',
        message: DEFAULT_CONFIRMATION_DIALOG_MESSAGE,
        onConfirm: {
          type: PYTHON_CALL,
          cmd: command,
          args,
        },
      }),
    );
  };

  const message = 'IMPORTING MODEL';
  const buttonLabel = 'Import';

  // Determine callback based on model state
  const callback =
    currentModelState === MODEL_STATE.INSTANTIATED || currentModelState === MODEL_STATE.SIMULATED
      ? (cmd: string, args: Record<string, any>) => {
          handleConfirmation(cmd, args);
        }
      : undefined;

  return (
    <>
      <ActionDialog
        command={command}
        message={message}
        buttonLabel={buttonLabel}
        args={{
          fileName,
          modFolder,
          loadMod,
          compileMod,
        }}
        title={title}
        isFormValid={isFormValid}
        callback={callback}
        open={open}
        onRequestClose={onRequestClose}
        {...otherProps}
      >
        <Box>
          <TextField
            variant="filled"
            fullWidth
            value={fileName || ''}
            onChange={(e) => onFilePathChange(e.target.value)}
            label="Choose file"
            helperText={extension ? `Only ${extension} files` : ''}
            sx={{
              '& .MuiFilledInput-root': {
                '&::before': {
                  display: 'none',
                },
              },
            }}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <Tooltip title="File explorer" placement="top">
                    <IconButton
                      edge="start"
                      onClick={() => showExplorerDialog('file', false, extension)}
                      sx={{ p: 0.5 }}
                    >
                      <FolderIcon />
                    </IconButton>
                  </Tooltip>
                </InputAdornment>
              ),
            }}
          />
          {modFileSelector && (
            <TextField
              variant="filled"
              fullWidth
              label="Path to mod files"
              value={modFolder}
              onChange={(e) => onModFolderPathChange(e.target.value)}
              helperText="Important: if external mod files are required please select the mod folder path"
              sx={{
                mt: 2,
                '& .MuiFilledInput-root': {
                  '&::before': {
                    display: 'none',
                  },
                },
              }}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <Tooltip title="File explorer" placement="top">
                      <IconButton
                        edge="start"
                        onClick={() => showExplorerDialog('modFolder', true, false)}
                        sx={{ p: 0.5 }}
                      >
                        <FolderIcon />
                      </IconButton>
                    </Tooltip>
                  </InputAdornment>
                ),
              }}
            />
          )}
          <Checkbox
            fullWidth
            noBackground
            label="Compile mod files"
            checked={compileMod}
            onChange={() => setCompileMod((prev) => !prev)}
          />
        </Box>
      </ActionDialog>

      <FileBrowser
        open={explorerDialogOpen}
        exploreOnlyDirs={exploreOnlyDirs}
        filterFiles={filterFiles}
        onRequestClose={closeExplorerDialog}
      />
    </>
  );
};

export default ImportFileDialog;

